package gateway.plugins.divide;

import gateway.ServicesHolder;
import gateway.WebContext;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadLocalRandom;

@Slf4j
public class RandomLoadBalance implements LoadBalance{
    @Override
    public String load(WebContext webContext) {
        String serviceName = webContext.getServiceName();
        int addressCacheSize = ServicesHolder.addressSize(serviceName);
        String address = null;
        if (addressCacheSize > 0) {
            if (addressCacheSize == 1) {
                address = ServicesHolder.getAddress(serviceName, 0);
            } else {
                address = ServicesHolder.getAddress(serviceName, ThreadLocalRandom.current().nextInt(addressCacheSize));
            }
            log.info(">>>get only address node:" + address);
        }
        return address;
    }
}
